package cn._51doit.flink.day02;

import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.util.Arrays;
import java.util.List;

/**
 * Source 如果在run方法中，执行的逻辑，没有while循环，执行完成后，job就退出，所以这样的Source是有限的数据源
 */
public class CustomSource1 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //可以认为设置执行环境的并行度
        //env.setParallelism(6);
        //System.out.println(env.getParallelism());

        DataStreamSource<String> lines = env.addSource(new MySource1());

        lines.print();

        env.execute();


    }

    private static class MySource1 implements SourceFunction<String> {

        /**
         * Source负责读取数据，然后使用SourceContext将数据输出给后面的算子使用
         * @param ctx
         * @throws Exception
         */
        @Override
        public void run(SourceContext<String> ctx) throws Exception {
            System.out.println("run method invoked !!!");
            List<String> words = Arrays.asList("spark", "hadoop", "flink", "hive", "hbase");
            for (String word : words) {
                //将数据输出
                ctx.collect(word);
            }
        }

        @Override
        public void cancel() {
            System.out.println("cancel method invoked @@@");
        }
    }
}
